import { getStorage, setStorage, removeStorage } from '@/utils/auth'
import { loginApi } from '@/api/api'
import { Module } from 'vuex'
import { RootState, UserState } from '../interface'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
interface ILoginForm {
  username: string
  password: string
}
const router = useRouter()
const userModule: Module<UserState, RootState> = {
  namespaced: true,
  state: {
    userInfo: getStorage('USER_INFO') || '',
    token: getStorage('USER_TOKEN'),
    name: '' || 'dhy123123',
    roles: []
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    }
  },
  actions: {
    login({ commit }, params: ILoginForm) {
      const { username, password } = params
      return new Promise((resolve, reject) => {
        loginApi(params)
          .then(res => {
            commit('SET_TOKEN', res.data.token)
            setStorage('USER_TOKEN', res.data.token)
            resolve(res)
            ElMessage({
              message: '登录成功',
              type: 'success'
            })
          })
          .catch(err => {
            console.log(err)
            reject(err)
          })
      })
    },
    loginOut({ commit }) {
      return new Promise((resolve, reject) => {
        removeStorage('USER_TOKEN')
        commit('SET_TOKEN', '')
        resolve(true)
        ElMessage({
          message: '退出登录',
          type: 'warning'
        })
        location.reload()
      })
    }
  }
}
export default userModule
